#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/spi.h"

#include "wizchip_conf.h"
#include "bsp_spi.h"
#include "PPPoE.h"
#include "socket.h" // Use socket

#define DATA_BUF_SIZE 2048
uint8_t gDATABUF[DATA_BUF_SIZE];

uint8_t pppoe_id[6] = "W5100S";
uint8_t pppoe_id_len = 6;
uint8_t pppoe_pw[7] = "WIZnet";
uint8_t pppoe_pw_len = 6;
uint8_t pppoe_ip[4] = {
    0,
};
uint16_t pppoe_retry_count = 0;

/* Network information to be configured. */
wiz_NetInfo net_info = {
    .mac = {0x00, 0x08, 0xdc, 0x11, 0x22, 0x33}, // Configured MAC address
    .ip = {192, 168, 1, 10},                     // Configured IP address
    .sn = {255, 255, 255, 0},                    // Configured subnet mask
    .gw = {192, 168, 1, 1},                      // Configured gateway
    .dns = {8, 8, 8, 8},                         // Configured domain address
    .dhcp = NETINFO_STATIC};                     // Configured dhcp model,NETINFO_DHCP:use dhcp; NETINFO_STATIC: use static ip.

wiz_NetInfo get_info;

int main()
{
    int32_t ret = 0;
    uint8_t str[15];
    struct repeating_timer timer; // Define the timer structure

    /* MCU init */
    stdio_init_all();              // Initialize the main control peripheral
    wizchip_initialize();          // Initialize the chip interface
    wizchip_setnetinfo(&net_info); // Configure once first

    printf("wiznet chip PPPOE example.\r\n");

    while (1)
    {
        ret = ppp_start(gDATABUF); // ppp start function
        if (ret == PPP_SUCCESS || pppoe_retry_count > PPP_MAX_RETRY_COUNT)
        {
            break; // PPPoE Connected or connect failed by over retry count
        }
            
    }
    if (ret == PPP_SUCCESS) // 1 : success
    {

        printf("\r\n<<<< PPPoE Success >>>>\r\n");
        printf("Assigned IP address : %d.%d.%d.%d\r\n", pppoe_ip[0], pppoe_ip[1], pppoe_ip[2], pppoe_ip[3]);

        printf("\r\n==================================================\r\n");
        printf("    AFTER PPPoE, Net Configuration Information        \r\n");
        printf("==================================================\r\n");

        getSHAR(str);
        printf("MAC address  : %x:%x:%x:%x:%x:%x\r\n", str[0], str[1], str[2], str[3], str[4], str[5]);
        getSUBR(str);
        printf("SUBNET MASK  : %d.%d.%d.%d\r\n", str[0], str[1], str[2], str[3]);
        getGAR(str);
        printf("G/W IP ADDRESS : %d.%d.%d.%d\r\n", str[0], str[1], str[2], str[3]);
        getSIPR(str);
        printf("SOURCE IP ADDRESS : %d.%d.%d.%d\r\n\r\n", str[0], str[1], str[2], str[3]);
    }
    else // failed
    {
        printf("\r\n<<<< PPPoE Failed >>>>\r\n");
        wizchip_setnetinfo(&net_info);        // Configuring Network Information
        print_network_information(&get_info); // Read back the configuration information and print it
    }

    while (1)
    {
    }
}
